<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 6.3.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha256-AbA177XfpSnFEvgpYu1jMygiLabzPCJCRIBtR5jGc0k=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"fengxun2017.github.io","root":"/","images":"/images","scheme":"Muse","darkmode":false,"version":"8.13.2","exturl":false,"sidebar":{"position":"right","display":"hide","padding":18,"offset":12},"copycode":{"enable":false,"style":null},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"}}</script><script src="/js/config.js"></script>

    <meta name="description" content="FreeRTOS提供的软件定时器，在使用上有几个需要开发者注意的事项。如软件定时器可以识别的基本时间单位，软件定时器服务任务的优先级设置的是否合适，以及软件定时器超时回调函数中不要使用会让当前任务（软件定时器服务任务）进入阻塞态的 FreeRTOS API。">
<meta property="og:type" content="article">
<meta property="og:title" content="FreeRTOS-软件定时器使用注意事项">
<meta property="og:url" content="http://fengxun2017.github.io/2022/12/26/FreeRTOS-note-on-timer-use/index.html">
<meta property="og:site_name" content="fx">
<meta property="og:description" content="FreeRTOS提供的软件定时器，在使用上有几个需要开发者注意的事项。如软件定时器可以识别的基本时间单位，软件定时器服务任务的优先级设置的是否合适，以及软件定时器超时回调函数中不要使用会让当前任务（软件定时器服务任务）进入阻塞态的 FreeRTOS API。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://fengxun2017.github.io/2022/12/26/FreeRTOS-note-on-timer-use/timer-task-schema.png">
<meta property="article:published_time" content="2022-12-25T16:00:00.000Z">
<meta property="article:modified_time" content="2023-02-02T14:04:16.992Z">
<meta property="article:author" content="feng xun">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://fengxun2017.github.io/2022/12/26/FreeRTOS-note-on-timer-use/timer-task-schema.png">


<link rel="canonical" href="http://fengxun2017.github.io/2022/12/26/FreeRTOS-note-on-timer-use/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"http://fengxun2017.github.io/2022/12/26/FreeRTOS-note-on-timer-use/","path":"2022/12/26/FreeRTOS-note-on-timer-use/","title":"FreeRTOS-软件定时器使用注意事项"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>FreeRTOS-软件定时器使用注意事项 | fx</title>
  






  <script async defer data-website-id="" src=""></script>

  <script defer data-domain="" src=""></script>

  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
  <a target="_blank" rel="noopener" href="https://github.com/fengxun2017" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#70B7FD; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">fx</p>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">FreeRTOS交流QQ群-663806972 BLE学习交流群-498676838</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li>
  </ul>
</nav>




</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E8%BD%AF%E4%BB%B6%E5%AE%9A%E6%97%B6%E5%99%A8%E5%8F%AF%E4%BB%A5%E8%AF%86%E5%88%AB%E7%9A%84%E5%9F%BA%E6%9C%AC%E6%97%B6%E9%97%B4%E5%8D%95%E4%BD%8D%EF%BC%9A"><span class="nav-number">1.</span> <span class="nav-text">软件定时器可以识别的基本时间单位：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E8%BD%AF%E4%BB%B6%E5%AE%9A%E6%97%B6%E5%99%A8%E6%9C%8D%E5%8A%A1%E4%BB%BB%E5%8A%A1-prvTimerTask-%E4%BC%98%E5%85%88%E7%BA%A7%E7%9A%84%E5%BD%B1%E5%93%8D%EF%BC%9A"><span class="nav-number">2.</span> <span class="nav-text">软件定时器服务任务(prvTimerTask)优先级的影响：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E4%B8%8D%E8%A6%81%E5%9C%A8%E8%B6%85%E6%97%B6%E5%9B%9E%E8%B0%83%E5%87%BD%E6%95%B0%E4%B8%AD%E8%B0%83%E7%94%A8%E4%BC%9A%E8%AE%A9%E4%BB%BB%E5%8A%A1%E9%98%BB%E5%A1%9E%E7%9A%84-API%EF%BC%9A"><span class="nav-number">3.</span> <span class="nav-text">不要在超时回调函数中调用会让任务阻塞的 API：</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">feng xun</p>
  <div class="site-description" itemprop="description">FreeRTOS交流QQ群-663806972 BLE学习交流群-498676838</div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">96</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">16</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
  </nav>
</div>
  <div class="cc-license site-overview-item animated" itemprop="license">
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" class="cc-opacity" rel="noopener" target="_blank"><img src="https://cdnjs.cloudflare.com/ajax/libs/creativecommons-vocabulary/2020.11.3/assets/license_badges/small/by_nc_sa.svg" alt="Creative Commons"></a>
  </div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://fengxun2017.github.io/2022/12/26/FreeRTOS-note-on-timer-use/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="feng xun">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="fx">
      <meta itemprop="description" content="FreeRTOS交流QQ群-663806972 BLE学习交流群-498676838">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="FreeRTOS-软件定时器使用注意事项 | fx">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          FreeRTOS-软件定时器使用注意事项
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2022-12-26 00:00:00" itemprop="dateCreated datePublished" datetime="2022-12-26T00:00:00+08:00">2022-12-26</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/FreeRTOS/" itemprop="url" rel="index"><span itemprop="name">FreeRTOS</span></a>
        </span>
    </span>

  
    <span class="post-meta-break"></span>
    <span class="post-meta-item" title="本文字数">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">本文字数：</span>
      <span>4.9k</span>
    </span>
    <span class="post-meta-item" title="阅读时长">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">阅读时长 &asymp;</span>
      <span>6 分钟</span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <center>
FreeRTOS提供的软件定时器，在使用上有几个需要开发者注意的事项。如软件定时器可以识别的基本时间单位，软件定时器服务任务的优先级设置的是否合适，以及软件定时器超时回调函数中不要使用会让当前任务（软件定时器服务任务）进入阻塞态的 FreeRTOS API。

</center>
<span id="more"></span>

<hr>
<h4 id="软件定时器可以识别的基本时间单位："><a href="#软件定时器可以识别的基本时间单位：" class="headerlink" title="软件定时器可以识别的基本时间单位："></a>软件定时器可以识别的基本时间单位：</h4><p>内核在每次<code>tick中断</code>发生时，会更新其内部的<code>tick</code>计数值加 1，来实现“感知时间”功能（更多信息可以参考文章：<a href="https://fengxun2017.github.io/2022/11/08/FreeRTOS-%E5%86%85%E6%A0%B8%E5%AF%B9%E6%97%B6%E9%97%B4%E7%9A%84%E6%B5%8B%E9%87%8F/">FreeRTOS-内核对时间的测量</a>）。而FreeRTOS提供的软件定时器，就是基于内核的<code>tick</code>计数值，来实现定时功能的。<br>例如，假设内核的<code>tick中断</code>产生的周期为100 ms，即每100 ms产生一次<code>tick中断</code>。如果一个定时器设定的超时时间为 1秒，那么识别该定时器超时，就是识别从该定时器启动后，<code>tick</code>计数值是否增加了10。</p>
<p>因此，<strong>FreeRTOS的软件定时器，可以识别的基本时间单位，就是内核产生<code>tick中断</code>的周期</strong>。<code>tick中断</code>周期由工程配置文件<code>FreeRTOSConfig.h</code>中定义的<code>configTICK_RATE_HZ</code>决定：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">define</span> configTICK_RATE_HZ			( ( TickType_t ) 100 )</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p>如上配置，就是设置内核产生<code>tick中断</code>的频率，为一秒产生100次<code>tick中断</code>，即周期即为 10 ms。 <strong>那么软件定时器，可以识别的基本时间单位就是10ms，可以设置的超时时间需要是 10ms 的 n 倍（n为大于 0的整数）</strong>。<br>如果设定的超时时间小于10ms，对定时器来说就是0，这个参数是不合法的，如果我们在开发阶段使能了断言宏，就会立刻报错。</p>
<p>在开发阶段，我们应该实现工程配置文件<code>FreeRTOSConfig.h</code>中的断言宏 <code>configASSERT</code>。很多配置、参数错误的问题，内核都会通过<code>configASSERT</code>给出错误的位置。例如一个简单的实现：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">extern</span> <span class="type">void</span> <span class="title function_">vAssertCalled</span><span class="params">( <span class="type">const</span> <span class="type">char</span> * pcFile, <span class="type">uint32_t</span> ulLine )</span>;</span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> configASSERT( x ) <span class="keyword">if</span>( ( x ) == 0 )	vAssertCalled( __FILE__, __LINE__ )</span></span><br></pre></td></tr></table></figure>
<p>然后在 main.c 或其它源文件中实现具体的函数，将出错的文件和具体行号信息输出：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">void</span> <span class="title function_">vAssertCalled</span><span class="params">( <span class="type">const</span> <span class="type">char</span> * pcFile, <span class="type">uint32_t</span> ulLine )</span>&#123;</span><br><span class="line">    <span class="comment">// 替换成自已的日志输出函数</span></span><br><span class="line">    SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;error at:%s, line:%d\r\n&quot;</span>, pcFile, ulLine);</span><br><span class="line">    <span class="keyword">for</span>(;;)&#123;&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>如果定义了上述宏<code>configASSERT</code>，那么在调用 API <code>xTimerCreate</code>创建软件定时器时，如果传入的定时器超时时间，小于软件定时器可以识别的基本时间单位，就会立刻给出错误提示。</p>
<h4 id="软件定时器服务任务-prvTimerTask-优先级的影响："><a href="#软件定时器服务任务-prvTimerTask-优先级的影响：" class="headerlink" title="软件定时器服务任务(prvTimerTask)优先级的影响："></a>软件定时器服务任务(prvTimerTask)优先级的影响：</h4><p>在之前的两篇文章<a href="https://fengxun2017.github.io/2022/11/27/FreeRTOS-principle_of_timer/">FreeRTOS-软件定时器的实现原理</a>和<a href="https://fengxun2017.github.io/2022/11/16/FreeRTOS-use-timer/">FreeRTOS-软件定时器的使用</a> 中，介绍了FreeRTOS的软件定时器，是一种分离式的设计。如下图所示：<br><img src="/2022/12/26/FreeRTOS-note-on-timer-use/timer-task-schema.png"><br>当我们调用软件定时器相关的 API 时，内部实际是发送了相应的定时器命令到<code>软件定时器专用的消息队列</code>中，而软件定时器服务任务（<code>或称为daemon task，使能FreeRTOS的软件定时器功能后，内核在启动时会自动创建该任务</code>），<strong>即上图中的prvTimerTask任务</strong>，会从软件定时器专用的消息队列中，提取定时器命令，并处理。<br>此外，每当有定时器的超时时间到达了，其超时回调函数（<code>创建定时器时的参数pxCallbackFunction</code>）也是在<code>prvTimerTask</code>任务中调用的。</p>
<p><code>prvTimerTask</code>任务的优先级，在工程配置文件<code>FreeRTOSConfig.h</code> 中定义，如下配置即将其优先级设置为 2</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">define</span> configTIMER_TASK_PRIORITY		( 2 )</span></span><br></pre></td></tr></table></figure>
<p>由于软件定时器的超时回调函数，是在<code>prvTimerTask</code>任务中调用的。因此，不能让<code>prvTimerTask</code>任务长时间得不到运行。否则，即使一些定时器超时了，由于<code>prvTimerTask</code>任务得不到运行，那么也就不能调用那些已经超时的定时器 的超时回调函数。</p>
<p>一个简单的测试实验，配置定时器服务任务<code>prvTimerTask</code>的优先级为2，并创建一个周期定时器，输出信息。再创建 2个优先级均为 3的任务<code>task_a</code>和<code>task_b</code>。<code>task_a</code>无限循环一直空跑，<code>task_b</code>则每秒输出一次信息。如下所示:</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 定时器超时回调函数</span></span><br><span class="line"><span class="type">void</span> <span class="title function_">timer_callback</span><span class="params">( TimerHandle_t timer )</span> &#123;</span><br><span class="line">    <span class="comment">// 替换成自己的日志输出</span></span><br><span class="line">    SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;timer timeout\n&quot;</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 空转，不让任务进入阻塞态，所以一直保持为就绪态（被运行时就是运行态）</span></span><br><span class="line"><span class="type">void</span> <span class="title function_">task_a</span><span class="params">( <span class="type">void</span> *pvParameters )</span> &#123;</span><br><span class="line">    <span class="keyword">for</span>(;;) &#123;</span><br><span class="line">    </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 每秒输出一次日志信息</span></span><br><span class="line"><span class="type">void</span> <span class="title function_">task_b</span><span class="params">( <span class="type">void</span> *pvParameters )</span> &#123;</span><br><span class="line">    <span class="keyword">for</span>(;;) &#123;</span><br><span class="line">        SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;task_b running\n&quot;</span>);</span><br><span class="line">        vTaskDelay(pdMS_TO_TICKS(<span class="number">1000</span>));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">void</span>)</span> &#123;</span><br><span class="line"></span><br><span class="line">    TickType_t timer_period = pdMS_TO_TICKS(<span class="number">1000</span>);</span><br><span class="line">    TimerHandle_t timer;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 创建定时器</span></span><br><span class="line">    timer = xTimerCreate(<span class="string">&quot;Timer&quot;</span>, timer_period, pdTRUE, <span class="literal">NULL</span>, timer_callback);</span><br><span class="line">    <span class="keyword">if</span>(<span class="literal">NULL</span> != timer ) &#123;</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 创建task_a， task_b</span></span><br><span class="line">        <span class="keyword">if</span> (pdPASS == xTaskCreate(task_a, <span class="string">&quot;task_a&quot;</span>, <span class="number">100</span>, <span class="literal">NULL</span>, <span class="number">3</span>, <span class="literal">NULL</span>)</span><br><span class="line">            &amp;&amp; pdPASS == xTaskCreate(task_b, <span class="string">&quot;task_b&quot;</span>, <span class="number">100</span>, <span class="literal">NULL</span>, <span class="number">3</span>, <span class="literal">NULL</span>))&#123;</span><br><span class="line">            </span><br><span class="line">            SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;start FreeRTOS\n&quot;</span>);</span><br><span class="line">            <span class="comment">// 启动定时器</span></span><br><span class="line">            xTimerStart(timer, <span class="number">0</span>);</span><br><span class="line">            vTaskStartScheduler();</span><br><span class="line">        &#125; </span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 正常启动后不会运行到这里</span></span><br><span class="line">    SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;insufficient resource\n&quot;</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span>( ;; );</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;    </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>烧录程序运行，只能看到 <code>task_b</code>的输出信息，看不到定时器超时回调函数的输出信息。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">start FreeRTOS</span><br><span class="line">task_b running</span><br><span class="line">task_b running</span><br><span class="line">task_b running</span><br><span class="line">task_b running</span><br><span class="line">task_b running</span><br><span class="line">....</span><br></pre></td></tr></table></figure>
<p>这是因为，<code>task_a</code>任务一直保持空转，没有调用任何会阻塞<code>task_a</code>任务的api，所以它一直是就绪态（被运行时，就是运行态），任务调度时总是选择处于就绪状态且优先级最高的那个任务，由于<code>task_a</code>优先级又比<code>prvTimerTask</code>高，所以每次都不会选择<code>prvTimerTask</code>任务。<code>task_b</code>能得到运行，是因为它和<code>task_a</code>优先级一样，所以<code>task_b</code>和<code>task_a</code>轮流运行（时间片调度）。</p>
<p>如果将<code>task_a</code>、<code>task_b</code>和<code>prvTimerTask</code>优先级都设置相同，默认就是轮流调用，此时就能看到定时器超时回调函数的输出信息。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">start FreeRTOS</span><br><span class="line">task_b running</span><br><span class="line">timer timeout</span><br><span class="line">task_b running</span><br><span class="line">timer timeout</span><br><span class="line">task_b running</span><br><span class="line">timer timeout</span><br><span class="line">....</span><br></pre></td></tr></table></figure>


<h4 id="不要在超时回调函数中调用会让任务阻塞的-API："><a href="#不要在超时回调函数中调用会让任务阻塞的-API：" class="headerlink" title="不要在超时回调函数中调用会让任务阻塞的 API："></a>不要在超时回调函数中调用会让任务阻塞的 API：</h4><p>原因还是如上一节所述，软件定时器的超时回调函数，是在<code>prvTimerTask</code>任务中调用的，如果你在某个定时器的超时回调函数中，调用了会让任务阻塞的API（<code>如vTaskDelay</code>），那么<code>prvTimerTask</code>任务就会进入阻塞态，会暂停运行，那么也就不能调用那些已经超时的定时器的超时回调函数了。超时回调函数需要等到<code>prvTimerTask</code>任务恢复就绪态，且<code>prvTimerTask</code>任务被调度时才能被调用。（ <code>但对于类似xQueueSend有超时参数的 API，当超时参数设置为 0时，任务是不会阻塞的，所以可以使用</code>）</p>
<p>一个简单的测试例子：创建两个单次触发的定时器<code>timer1</code>和<code>timer2</code>，超时时间均为 1秒钟，启动时先启动<code>timer1</code>。在<code>timer1</code>的超时回调函数中调用<code>vTaskDelay</code>，让其延迟 5秒钟。则可以观察到，<code>timer2</code>的超时回调函数，需要等到 5秒延迟结束后才会被调用。<br>代码如下：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="type">void</span> <span class="title function_">timer1_callback</span><span class="params">( TimerHandle_t timer )</span> &#123;</span><br><span class="line">    SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;timer1 timeout\n&quot;</span>);</span><br><span class="line">    <span class="comment">// 这里会让当前任务（prvTimerTask）阻塞</span></span><br><span class="line">    vTaskDelay(pdMS_TO_TICKS(<span class="number">5000</span>));</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="type">void</span> <span class="title function_">timer2_callback</span><span class="params">( TimerHandle_t timer )</span> &#123;</span><br><span class="line">    SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;timer2 timeout\n&quot;</span>);</span><br><span class="line">&#125;</span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">void</span>)</span> &#123;</span><br><span class="line"></span><br><span class="line">    TickType_t timer1_period = pdMS_TO_TICKS(<span class="number">1000</span>);</span><br><span class="line">    TickType_t timer2_period = pdMS_TO_TICKS(<span class="number">1000</span>);</span><br><span class="line"></span><br><span class="line">    TimerHandle_t timer1, timer2;</span><br><span class="line">    timer1 = xTimerCreate(<span class="string">&quot;Timer&quot;</span>, timer1_period, pdFALSE, <span class="literal">NULL</span>, timer1_callback);</span><br><span class="line">    timer2 = xTimerCreate(<span class="string">&quot;Timer2&quot;</span>, timer2_period, pdFALSE, <span class="literal">NULL</span>, timer2_callback);</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">if</span>(<span class="literal">NULL</span> != timer1 &amp;&amp; <span class="literal">NULL</span> != timer2) &#123;</span><br><span class="line">        SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;start FreeRTOS\n&quot;</span>);</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 超时时间相同，先启动 timer1</span></span><br><span class="line">        <span class="comment">// 则超时时间到达时,会先调用 timer1的超时回调</span></span><br><span class="line">        xTimerStart(timer1, <span class="number">0</span>);</span><br><span class="line">        xTimerStart(timer2, <span class="number">0</span>);</span><br><span class="line">        vTaskStartScheduler();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 正常启动后不会运行到这里</span></span><br><span class="line">    SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;insufficient resource\n&quot;</span>);</span><br><span class="line">    <span class="keyword">for</span>( ;; );</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;    </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>烧录运行可以看到如下输出信息：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">start FreeRTOS</span><br><span class="line">timer1 timeout</span><br><span class="line">timer2 timeout  # 5秒延迟后才能看到该信息</span><br></pre></td></tr></table></figure>

<br>
ps：需要注意文章代码中的日志输出函数，产品代码中如果需要使用的话，需要考虑线程安全性（多任务安全性），因为中断/任务切换可能发生在另一个任务正在输出日志但还未输出完的时候，这就可能造成日志错乱

<br>

<br>
FreeRTOS交流QQ群-663806972

<br>
<br>

<p>参考连接：<a target="_blank" rel="noopener" href="https://www.freertos.org/RTOS-software-timer-service-daemon-task.html">FreeRTOS software timers</a></p>

    </div>

    
    
    

    <footer class="post-footer">
          

<div class="post-copyright">
<ul>
  <li class="post-copyright-author">
      <strong>本文作者： </strong>feng xun
  </li>
  <li class="post-copyright-link">
      <strong>本文链接：</strong>
      <a href="http://fengxun2017.github.io/2022/12/26/FreeRTOS-note-on-timer-use/" title="FreeRTOS-软件定时器使用注意事项">http://fengxun2017.github.io/2022/12/26/FreeRTOS-note-on-timer-use/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>


        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2022/12/25/FreeRTOS-interrupt-nesting/" rel="prev" title="FreeRTOS-硬件中断嵌套模型和内核临界区">
                  <i class="fa fa-chevron-left"></i> FreeRTOS-硬件中断嵌套模型和内核临界区
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2023/01/03/FreeRTOS-mutex/" rel="next" title="FreeRTOS-使用互斥量（mutex）保护共享数据">
                  FreeRTOS-使用互斥量（mutex）保护共享数据 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2025</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">feng xun</span>
</div>
<div class="wordcount">
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-line"></i>
    </span>
      <span>站点总字数：</span>
    <span title="站点总字数">552k</span>
  </span>
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span>站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">11:30</span>
  </span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/muse/" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script>

  





  





</body>
</html>
